/*-------------------------------------------------------------------------
 - Copyright (c) 2024-2025 [XD-AMCC TEAM]
 - [XD-AMCC] is licensed under Mulan PSL v2.
 - You can use this software according to the terms and conditions of the Mulan PSL v2.
 - You may obtain a copy of Mulan PSL v2 at:
 -          http://license.coscl.org.cn/MulanPSL2
 - THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES
 - OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
 - TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 - See the Mulan PSL v2 for more details.
 ------------------------------------------------------------------------*/


/**
 * @brief Implement API for system date and time.
 *
 * @author  WXQ#XDU
 * @date    2024.11
 */

#include <time.h>

#include <../include/amcc_time.h>

#ifdef AMCC_BY_MSVC
#include <sys/timeb.h>
#else
#include <sys/time.h>
#endif // !AMCC_BY_MSVC

t_time amcc_get_time() {
    t_time result;
#ifdef AMCC_BY_MSVC
    struct _timeb tmval;
    _ftime( &tmval );
    result.tv_sec  = tmval.time;
    result.tv_msec = (int) (tmval.millitm);
#else
    struct timeval  tmval;
    gettimeofday(&tmval, NULL); // this is LINUX system call
    result.tv_sec  = tmval.tv_sec;
    result.tv_msec = (int)(tmval.tv_usec / 1000);
#endif

#if __STDC_VERSION__ >= 201112L // C11
    if ( 0 != localtime_s( &(result.tm), &(result.tv_sec) ) ) {
        result.tm = *localtime( &(result.tv_sec) );
    }
#else
    result.tm = *localtime( &(result.tv_sec) );
#endif

    result.tm.tm_year += 1900;
    result.tm.tm_mon  += 1;
    return result;
}

const char * amcc_get_timestring(t_time * pTime) {
    static char retText[80];
    t_time now ;
    if (NULL == pTime) {
        now = amcc_get_time();
        pTime = &now;
    }
    snprintf(retText, sizeof(retText)-1,
             "%04d-%02d-%02d %02d:%02d:%02d.%03d" ,
             (pTime->tm.tm_year), pTime->tm.tm_mon, pTime->tm.tm_mday,
             pTime->tm.tm_hour, pTime->tm.tm_min, pTime->tm.tm_sec,
             now.tv_msec );
    return retText;
}

